<template>
  <div class="health-charts">
    <div ref="healthCharts" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup name="PieEcharts" lang="ts">
import * as echarts from 'echarts';

const healthCharts = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

const props = defineProps({
  datas: {
    type: Array<any>,
    required: true,
    default: () => []
  }
});

watch(
  () => props.datas,
  (newDates: any[]) => {
    if (newDates && healthCharts.value) {
      updateChart();
    }
  },
  { immediate: true }
);

const updateChart = () => {
  if (!healthCharts.value) return;
  if (!chartInstance) {
    const chartInstance = echarts.init(healthCharts.value, 'macarons');
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: ['18-25', '26-35', '36-45', '46-55', '56-65', '65+'],
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            color: '#fff'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          minInterval: 1,
          splitNumber: 5,
          axisLabel: {
            color: '#fff',
            formatter: '{value} 人'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(60, 195, 245, 0.16)'
            }
          },
          axisTick: {
            lineStyle: {
              color: 'rgba(0, 249, 197, 0.30)'
            }
          }
        }
      ],
      series: [
        {
          label: {
            show: true,
            position: 'outside',
            formatter: function (e) {
              return e.value ? e.value : '';
            },
            color: '#03c782',
            fontSize: 16,
            fontWeight: 'bold'
          },
          name: '人数',
          type: 'bar',
          barWidth: 20,
          data: props.datas,
          color: ['#03c782'],
          itemStyle: {
            borderRadius: [5, 5, 0, 0]
          }
        }
      ]
    };
    chartInstance.setOption(option);
    window.addEventListener('resize', () => chartInstance?.resize());
  }
};

onMounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    window.removeEventListener('resize', () => chartInstance?.resize());
  }
});
</script>

<style scoped lang="scss">
.health-charts {
  width: 100%;
  height: calc(100% - 30px);
}
</style>
